package online.inote.naruto.api.access.admin.common.configure;

import online.inote.naruto.api.access.admin.common.annotation.Web;
import online.inote.naruto.api.access.admin.common.props.ApiAdminProperties;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.*;

import static online.inote.naruto.api.access.admin.common.constant.Scan.*;

/**
 * @description Naruto Api Access Admin Spring Configuration
 * @author XQF.Sui
 * @date 2021/08/03 10:25
 */
@Configuration
@Import(ApiAdminProperties.class)
@ComponentScan(NARUTO_API_ACCESS_ADMIN_SPRING_SCAN_PATH)
@EntityScan(NARUTO_API_ACCESS_ADMIN_JPA_ENTITY_SCAN_PATH)
@EnableJpaRepositories(NARUTO_API_ACCESS_ADMIN_JPA_REPOSITORIES_SCAN_PATH)
public class NarutoApiAccessAdminSpringConfiguration implements WebMvcConfigurer {

  private static final String LOGIN_URL = "/user/login";
  private final String baseUrl;

  NarutoApiAccessAdminSpringConfiguration(ApiAdminProperties props) {
    this.baseUrl =
        StringUtils.trimTrailingCharacter(props.getApi().getContextPath(), '/') + "/naruto-ui/";
  }

  @Configuration
  class NarutoSecurityWebPathMatchConfiguration implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
      configurer.addPathPrefix(baseUrl, c -> c.isAnnotationPresent(Web.class));
    }
  }

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
        .addResourceHandler(baseUrl + "**")
        .addResourceLocations("classpath:/META-INF/resources/webjars/naruto-ui/")
        .resourceChain(false);
  }

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController(baseUrl).setViewName("forward:" + baseUrl + "/index.html");
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry
        .addInterceptor(loginInterceptor())
        .addPathPatterns(baseUrl + "/**")
        .excludePathPatterns(baseUrl + LOGIN_URL);
  }

  @Bean
  LoginInterceptor loginInterceptor() {
    return new LoginInterceptor();
  }
}
